﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Text;
using System.Configuration;

public partial class Student_Score : System.Web.UI.Page
{
    private UserControls_ScoreCardControl controlObj = new UserControls_ScoreCardControl();
    int testid;
    Information ansObj = new Information();
    string attemptId;
    ArrayList arrAllQuestionobj = new ArrayList();


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["AttemptId"] == null)
            {
                getValues();
            }
            else
                setValues();
        }
        testid = Convert.ToInt32(Session["TestId"]);
        attemptId = Session["AttemptId"].ToString();
    }

    private void getValues()
    {
        controlObj = (UserControls_ScoreCardControl)LoadControl("~/UserControls/ScoreCardControl.ascx");
        ControlPlace.Controls.Add(controlObj);
        testid = Int32.Parse(Request.QueryString["TestId"].ToString());
        Session["TestId"] = testid;
        lablTimeTaken.Text = Request.QueryString["TimeTaken"].ToString();
        GetHeaderFields();
        controlObj.fillQuestionDs(testid);
        status(testid, controlObj);
        string Qid = "", OptionId = "";
        ansObj = (Information)Session["Answers"];
        foreach (var s in ansObj.answer)
        {
            Qid += s.Key + "|";
            OptionId += s.Value + "&";
        }
        DataTable dtTestAttempt = new DataTable();
        dtTestAttempt = AdminCreateTestDAL.GetTestAttemptInfo(Session["UserId"], testid);
        int testAttNo;
        if (dtTestAttempt.Rows.Count > 0)
        {
            testAttNo = Convert.ToInt32(dtTestAttempt.Rows[dtTestAttempt.Rows.Count - 1][0]);
            testAttNo++;
        }
        else
            testAttNo = 1;

        DataTable dtAtt = AdminCreateTestDAL.SetTestAttempt(testid, lablPassFail.Text, Convert.ToInt32(lablMarksScored.Text), testAttNo, Session["UserId"], Qid, OptionId, Convert.ToInt32(lablTimeTaken.Text));

        Session["AttemptId"] = dtAtt.Rows[0][0];
        Session["Pos"] = 0;
        controlObj.pos = Convert.ToInt32(Session["Pos"]);
        attemptId = Session["AttemptId"].ToString();

        DataTable dtEmail = new DataTable();
        dtEmail = AdminCreateTestDAL.GetTestAttemptInfoForMail(Convert.ToInt32(attemptId));
        StringBuilder sbMail = new StringBuilder();
        sbMail.Append("<table width='70%'><tr><td>TestId:<b> " + dtEmail.Rows[0][0].ToString() + "</b></td></tr>");
        sbMail.Append("<tr><td>Test Name:<b> " + dtEmail.Rows[0][1].ToString() + "</b></td></tr><tr><td></td></tr>");
        sbMail.Append("<tr><td>Subject Name:<b> " + dtEmail.Rows[0][2].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>No Of Questions:<b> " + dtEmail.Rows[0][3].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>CutOffMarks:<b> " + dtEmail.Rows[0][4].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>Expiry Date:<b> " + dtEmail.Rows[0][5].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>Duration:<b> " + dtEmail.Rows[0][6].ToString() + "<b></td></tr></table>");
        sbMail.Append("<tr><td>User Name:<b> " + dtEmail.Rows[0][7].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>Attempt No:<b> " + dtEmail.Rows[0][8].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>Attempt Date:<b> " + dtEmail.Rows[0][9].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>Result:<b> " + dtEmail.Rows[0][10].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>Score:<b> " + dtEmail.Rows[0][11].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td>Time Taken:<b> " + dtEmail.Rows[0][12].ToString() + "</b></td></tr></table>");
        sbMail.Append("<tr><td><a href='http://www.skillify.net?AttemptId="+attemptId+"'>Go to score card</a>" + "</td></tr></table>");

        DataTable dtCreaterMail = new DataTable();
        dtCreaterMail = AdminCreateTestDAL.GetCreaterId(Convert.ToInt32(attemptId));

        ConfigurationManager.AppSettings["ContactEmailTo"] = dtCreaterMail.Rows[0][0].ToString();
        if (SendEmail(ConfigurationManager.AppSettings["ContactEmailFrom"], ConfigurationManager.AppSettings["ContactEmailPassword"], ConfigurationManager.AppSettings["ContactEmailTo"], "Skillify.net - Test \"" + dtEmail.Rows[0][1].ToString() + "\" is attempted by " + dtEmail.Rows[0][7].ToString(), sbMail.ToString(), System.Web.Mail.MailFormat.Html, "") == true)
        {

        }

        controlObj.displayQuestion(controlObj.pos, attemptId);
    }


    public static bool SendEmail(string pGmailEmail, string pGmailPassword, string pTo, string pSubject, string pBody, System.Web.Mail.MailFormat pFormat, string pAttachmentPath)
    {
        try
        {
            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                              "smtp.gmail.com");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                              "465");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                              "2");

            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusername",
                pGmailEmail);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
                 pGmailPassword);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
                 "true");
            myMail.From = pGmailEmail;
            myMail.To = pTo;
            myMail.Subject = pSubject;
            myMail.BodyFormat = pFormat;
            myMail.Body = pBody;


            System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
            System.Web.Mail.SmtpMail.Send(myMail);
            return true;
        }
        catch (Exception ex)
        {
            throw;
        }
    }


    private void status(int testid, UserControls_ScoreCardControl objDs)
    {
        int count = 0;
        string Value = "";
        DataTable dtAnswer = new DataTable();
        for (int i = 0; i < objDs.dsQustn.Tables[0].Rows.Count; i++)
        {
            dtAnswer = DALKAT.GetRightOptionId(Int32.Parse(objDs.dsQustn.Tables[0].Rows[i][2].ToString()));
            ansObj = (Information)Session["Answers"];
            foreach (var s in ansObj.answer)
            {
                if (s.Key.ToString() == objDs.dsQustn.Tables[0].Rows[i][2].ToString())
                {
                    if (s.Value.Contains('|'))
                    {
                        Value = s.Value.Substring(0, s.Value.Length - 1);
                    }
                    else
                        Value = s.Value.ToString();
                    if (Value.Trim() == dtAnswer.Rows[0][0].ToString().Trim())
                        count++;
                }
            }
        }
        if (Convert.ToInt32(lablCutOff.Text) > 0)
        {
            lablPassFail.Visible = true;
            if (count >= Convert.ToInt32(lablCutOff.Text))
            {
                lablPassFail.Text = "PASS";
                lablPassFail.ForeColor = System.Drawing.Color.Green;
                AdminCreateTestDAL.updateTestStatus(testid, Session["UserId"], "Completed");
            }
            else
            {
                lablPassFail.Text = "FAIL";
                lablPassFail.ForeColor = System.Drawing.Color.Red;
                AdminCreateTestDAL.updateTestStatus(testid, Session["UserId"], "Scheduled");
            }
        }
        if (Convert.ToInt32(lablCutOff.Text) == 0)
        {
            AdminCreateTestDAL.updateTestStatus(testid, Session["UserId"], "Completed");
            lablPassFail.Text = "PASS";
        }
        lablMarksScored.Text = count.ToString();
    }

    private void GetHeaderFields()
    {
        DataTable dtFields;
        dtFields = DALKAT.GetTestInProgressFields(testid);
        if (dtFields.Rows.Count != 0)
        {
            lablTestName.Text = dtFields.Rows[0][1].ToString();
            lablTotalQues.Text = dtFields.Rows[0][2].ToString();
            lablCutOff.Text = dtFields.Rows[0][4].ToString();
        }
    }

    private void setValues()
    {
        attemptId=Request.QueryString["AttemptId"].ToString();
        Session["AttemptId"] = attemptId;
        controlObj = (UserControls_ScoreCardControl)LoadControl("../UserControls/ScoreCardControl.ascx");
        ControlPlace.Controls.Add(controlObj);
        DataTable dtTestAttempt = new DataTable();
        dtTestAttempt = AdminCreateTestDAL.GetTestCompletedAttemptAllInfo(Convert.ToInt32(Request.QueryString["AttemptId"]));
        testid = Convert.ToInt32(dtTestAttempt.Rows[0][2]);
        object user = dtTestAttempt.Rows[0][1];
        Session["TestId"] = testid;
        GetHeaderFields();
        controlObj.fillQuestionDs(testid);
        DataTable dtAttempt = new DataTable();
        dtAttempt = AdminCreateTestDAL.GetTestAttemptAllInfo(user, testid);
        if (Convert.ToInt32(lablCutOff.Text) > 0)
        {
            lablPassFail.Visible = true;
            lablPassFail.Text = dtAttempt.Rows[0][2].ToString();
            if (lablPassFail.Text == "PASS")
            {
                lablPassFail.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                lablPassFail.ForeColor = System.Drawing.Color.Red;
            }

        }
        lablTimeTaken.Text = dtTestAttempt.Rows[0][7].ToString();
        lablMarksScored.Text = dtTestAttempt.Rows[0][5].ToString();
        Session["Pos"] = 0;
        controlObj.pos = Convert.ToInt32(Session["Pos"]);
        controlObj.displayQuestion(controlObj.pos, attemptId);
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        controlObj = (UserControls_ScoreCardControl)LoadControl("../UserControls/ScoreCardControl.ascx");
        ControlPlace.Controls.Add(controlObj);
        controlObj.fillQuestionDs(testid);
        controlObj.pos = Convert.ToInt32(Session["Pos"]);
        controlObj.pos++;
        Session["Pos"] = controlObj.pos;
        if (controlObj.pos > controlObj.dsQustn.Tables[0].Rows.Count - 1)
        {
            controlObj.pos = controlObj.dsQustn.Tables[0].Rows.Count - 1;
            Session["Pos"] = controlObj.pos;
        }
        controlObj.displayQuestion(controlObj.pos, attemptId);
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        controlObj = (UserControls_ScoreCardControl)LoadControl("../UserControls/ScoreCardControl.ascx");
        ControlPlace.Controls.Add(controlObj);
        controlObj.fillQuestionDs(testid);
        controlObj.pos = Convert.ToInt32(Session["Pos"]);
        controlObj.pos--;
        Session["Pos"] = controlObj.pos;
        if (controlObj.pos < 0)
        {
            controlObj.pos = 0;
            Session["Pos"] = controlObj.pos;
        }
        controlObj.displayQuestion(controlObj.pos, attemptId);
    }

    protected void btnShowAll_Click(object sender, EventArgs e)
    {
        btnNext.Visible = false;
        btnBack.Visible = false;
        btnShowAll.Visible = false;
        btnShowOneByOne.Visible = true;
        controlObj.fillQuestionDs(testid);
        UserControls_ScoreCardControl tempObj;
        for (int k = 0; k < controlObj.dsQustn.Tables[0].Rows.Count; k++)
        {
            arrAllQuestionobj.Add(LoadControl("../UserControls/ScoreCardControl.ascx"));
            tempObj = (UserControls_ScoreCardControl)(arrAllQuestionobj[k]);
            ControlPlace.Controls.Add(tempObj);
            tempObj.fillQuestionDs(testid);
            tempObj.displayQuestion(k, attemptId);
        }
    }

    protected void btnShowOneByOne_Click(object sender, EventArgs e)
    {
        btnNext.Visible = true;
        btnBack.Visible = true;
        btnShowAll.Visible = true;
        btnShowOneByOne.Visible = false;
        controlObj = (UserControls_ScoreCardControl)LoadControl("../UserControls/ScoreCardControl.ascx");
        ControlPlace.Controls.Add(controlObj);
        controlObj.fillQuestionDs(testid);
        controlObj.pos = 0;
        controlObj.displayQuestion(controlObj.pos, attemptId);
        Session["Pos"] = 0;
    }

    protected void btnShowRank_Click(object sender, EventArgs e)
    {
        attemptId = Session["AttemptId"].ToString();
        DataTable dtTestId = new DataTable();
        dtTestId = AdminCreateTestDAL.GetTestIdBasedOnAttemptId(Convert.ToInt32(attemptId));
        int testId = Convert.ToInt32(dtTestId.Rows[0][0]);
        Response.Redirect("~/Student/ViewTestRank.aspx?TestId=" + testId.ToString());

    }
}